using FytSoa.Domain.Hr;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Hr;

/// <summary>
/// 人力-调动表服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v8")]
public class HrTransferService : IApplicationService 
{
    private readonly SugarRepository<HrTransfer> _thisRepository;
    private readonly SugarRepository<HrEmployee> _employeeRepository;
    public HrTransferService(SugarRepository<HrTransfer> thisRepository
    ,SugarRepository<HrEmployee> employeeRepository)
    {
        _thisRepository = thisRepository;
        _employeeRepository = employeeRepository;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<HrTransferDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Reason.Contains(param.Key))
            .Includes(m=>m.EmployeeObj)
            .Includes(m=>m.OutOrgObj)
            .Includes(m=>m.InOrgObj)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<HrTransferDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<HrTransferDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(m=>m.EmployeeObj)
            .Includes(m=>m.OutOrgObj)
            .FirstAsync(m=>m.Id==id);
        return model.Adapt<HrTransferDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(HrTransferDto model)
    {
        await _employeeRepository.UpdateAsync(m => new HrEmployee()
        {
            OrganizationId = model.InOrgId
        },m=>m.Id==model.EmployeeId);
        return await _thisRepository.InsertAsync(model.Adapt<HrTransfer>());
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(HrTransferDto model)
    {
        await _employeeRepository.UpdateAsync(m => new HrEmployee()
        {
            OrganizationId = model.InOrgId
        },m=>m.Id==model.EmployeeId);
        return await _thisRepository.UpdateAsync(model.Adapt<HrTransfer>());
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody]List<long> ids) =>
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
}
